package com.kvn.hotcompiler.factory;

import java.io.File;
import java.net.URISyntaxException;

import com.kvn.hotcompiler.core.DynaCodeGenerator;

/**
 * 动态代码工厂
 * @author wzy
 *
 */
public class DynaCodeFactory {
	private static final String SOURCE_DIR = "dynacode";
	private DynaCodeGenerator dynaCodeGenerator;
	
	private DynaCodeFactory() {
		super();
	}
	
	private static class SINGLETON {
		public static DynaCodeFactory INSTANCE = new DynaCodeFactory();
	}
	

	public static DynaCodeFactory init(){
		DynaCodeFactory factory = DynaCodeFactory.SINGLETON.INSTANCE;
		if(factory.dynaCodeGenerator != null){
			return factory;
		}
		
		DynaCodeGenerator dynacode = new DynaCodeGenerator();
		try {
			dynacode.addSourceDir(new File(DynaCodeFactory.class.getClassLoader().getResource("META-INF" + File.separator + SOURCE_DIR).toURI()));
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		factory.dynaCodeGenerator = dynacode;
		return factory;
	}
	
	
	@SuppressWarnings("unchecked")
	public static <T> T createNewestSingleton(Class<T> interfaceOfTargetClass, String targetClassFullPath){
		DynaCodeFactory factory = DynaCodeFactory.SINGLETON.INSTANCE;
		return (T) factory.dynaCodeGenerator.newProxyInstance(interfaceOfTargetClass, targetClassFullPath);
	}

}
